package com.xuan_poi.easyUtil;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author renzhengxuan
 * @date 2021/4/14
 */
@Slf4j
public class ExcelUtil {
    /**
     * 读取excel工具类
     *
     * @param file
     * @param entity
     * @param <T>
     * @return
     */
    public static <T> List<T> imporeExcel(File file, Class<T> entity) {
        List<T> list = new ArrayList<>();
        try {
            //获取到读取的文件
            EasyExcel.read(file).head(entity).sheet()
                    .registerReadListener(new AnalysisEventListener<T>() {
                        @Override
                        public void invoke(T t, AnalysisContext analysisContext) {
                            list.add(t);
                        }
                        @Override
                        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                            log.info("读取文件成功");
                        }
                    }).doRead();
        } catch (Exception e) {
            log.info("读取文件失败");
        }
        return list;
    }

    /**
     * 文件导出
     * @param path
     * @param entity
     * @param list
     * @param <T>
     */
    public static <T> void exporeExcel(String path, Class<T> entity, List<T> list) {
        EasyExcel.write(path, entity).sheet().doWrite(list);
    }
}
